<template>
	<view class="uploadImageBox">
		<view style="display: flex;flex-wrap: wrap;">
			<view v-for="(item,imageIndex) in imageList" :key="imageIndex" class="imageAddBox">
				<view v-if="!item.upload" class="uploadBox">
					<u-loading-icon color='#fff'></u-loading-icon>
					<view>
						上传中
					</view>
				</view>
				<image mode="aspectFill" :src="item.coverUrl" />
				<view class="del" v-if="item.upload" @click="del(item)">
					<view>
						<u-icon name="close" color="#fff" size="20rpx"></u-icon>
					</view>
				</view>
				<view v-if="item.upload" class="success">
					<view>
						<u-icon name="checkmark" color="#fff" size="20rpx"></u-icon>
					</view>
				</view>
				<view v-if="item.upload" class="title" @click="openModal(imageIndex) ">
					<u--text v-if="item.title" lines='2' size='24rpx' color='#fff' :text='item.title'></u--text>
					<u--text v-else lines='2' size='24rpx' align='center' color='#fff' text='图片描述'></u--text>
				</view>
			</view>
			<view v-if="imageList.length" class="imageAddBox" @click="upload">
				<u-icon name="camera-fill" color="#D3D4D6" size="26"></u-icon>
			</view>
		</view>
		<root-portal>
			<u-modal title='请输入图片描述' :show="show" showCancelButton @cancel='cancel' @confirm="confirm" ref="uModal">
				<u--textarea @change='textChange' :disabled="disabled" v-if='show' v-model="imageList[titleIndex].title"
					placeholder="请输入图片描述"></u--textarea>
			</u-modal>
		</root-portal>
	</view>
</template>

<script>
	import VODUpload from '../aliyun-vod/aliyun-upload-sdk-1.0.1.min.js'
	export default {
		props: ['imageUrl', 'propsIndex', 'imageShow'],
		data() {
			return {
				imageList: [

				],
				imageUpload: {
					aliyun: null,
				},
				index: 0,
				show: false,
				title: null,
				titleIndex: 0,
				disabled: false,
				token: uni.getStorageSync('token')
			}
		},
		mounted() {
			this.aliyunInit()
			if (this.imageUrl?.length) {
				this.imageList = this.imageUrl
			}
			if (this.propsIndex != 1) {
				if (this.imageShow == 'photo') {
					this.upload()
				} else {
					this.chatUpload()
				}
			}
		},
		methods: {
			confirm() {
				const {
					id,
					title
				} = this.imageList[this.titleIndex]
				if (this.disabled) return
				if (!this.imageList[this.titleIndex].title) {
					uni.$u.toast('请输入描述')
					return
				}
				this.disabled = true
				this.$api_company.Image.Update(id, {
					title
				}).then(res => {
					uni.$u.toast('设置成功')
					this.show = false
					this.disabled = false
					this.titleIndex = 0
				}).catch(err => {
					uni.$u.toast(err.message)
					this.disabled = false
					this.titleIndex = 0
					this.show = false
				})
			},
			openModal(imageIndex) {
				this.titleIndex = imageIndex
				this.title = this.imageList[imageIndex].title
				this.show = true
			},
			cancel() {
				this.imageList[this.titleIndex].title = this.title
				this.titleIndex = 0
				this.show = false
			},
			chatUpload() {
				wx.chooseMessageFile({
					count: 9,
					type: 'image',
					success: (res) => {
						res.tempFiles.forEach((item, index) => {
							this.imageList.push({
								url: item.path,
								coverUrl: item.path,
								id: null,
								upload: false,
								title: ''
							})
						})
						this.$emit('changeImageList', this.imageList)
						const length = this.imageList.filter(item => item.upload).length
						if (length) {
							this.index = length
						}
						this.startUpload()

					},
					fail: (err) => {
						console.log(err)
						if (!this.imageList.length) {
							this.$emit('close')
						}
					}
				})
			},
			upload() {
				uni.chooseImage({
					count: 9,
					success: (res) => {
						res.tempFilePaths.forEach((item, index) => {
							this.imageList.push({
								url: item,
								coverUrl: item,
								id: null,
								upload: false,
								title: ''
							})
						})
						this.$emit('changeImageList', this.imageList)
						const length = this.imageList.filter(item => item.upload).length
						if (length) {
							this.index = length
						}
						this.startUpload()
					},
					fail: () => {
						if (!this.imageList.length) {
							this.$emit('close')
						}
					}
				})
			},
			startUpload() {
				if(!this.imageList[this.index].url)return
				uni.uploadFile({
					url: this.$config.url+'/company/api/activity/image/check', //仅为示例，非真实的接口地址
					filePath: this.imageList[this.index].url,
					name: 'file',
					header: {
						'Content-Type': 'application/json;charset=UTF-8',
						'Authorization': "Bearer " + this.token
					},
					success: (res) => {
						const {code,message}=JSON.parse(res.data)
						if(code==0){
							this.imageUpload.aliyun.addFile(this.imageList[this.index], null, null, null,
								'{"Vod":{}}')
							this.imageUpload.aliyun.startUpload();
						}else{
							uni.$u.toast(message)
							this.imageList=this.imageList.filter(item=>item.upload)
						}
					},
					fail: (err) => {
						console.log(err);
					}
				});
				
			},
			aliyunInit() {
				// 阿里云初始化
				this.imageUpload.aliyun = new VODUpload({
					//阿里云的账号ID，不能为空，您可以使用阿里云账号访问账号中心（https://account.console.aliyun.com/），即可查看账号ID。            
					userId: "1386228921490232",
					//上传到点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1，更多信息请参见媒体上传概述
					region: "cn-shanghai",
					//网络原因失败时，重新上传次数，默认为3
					retryCount: 3,
					//网络原因失败时，重新上传间隔时间，默认为2秒
					retryDuration: 2,
					addFileSuccess: function(uploadInfo) {},
					onUploadstarted: (uploadInfo) => {
						this.$api_company.Aliyun.Image.Create().then(res => {
							this.imageList[this.index].id = res.data.image_id
							this.imageList[this.index].url = res.data.image_url
							this.imageUpload.aliyun.setUploadAuthAndAddress(
								uploadInfo,
								res.data.upload_auth,
								res.data.upload_address,
								res.data.image_id
							);
						})
					},
					onUploadSucceed: (uploadInfo) => {
						this.$api_company.Image.Add({
							media_id: this.imageList[this.index].id,
							url: this.imageList[this.index].url
						}).then(res => {
							this.imageList[this.index].upload = true
							this.imageList[this.index].id = res.data.image.id
							this.index++
							if (this.index >= this.imageList.length) {
								uni.$u.toast('上传完成')
								return
							}
							this.startUpload()
							this.$emit('changeImageList', this.imageList)
						})
					},
					onUploadFailed: (uploadInfo, code, message) => {
						uploader.stopUpload();
					},
					onUploadprogress: (uploadInfo, totalSize, loadedPercent) => {},
					onUploadTokenExpired: (uploadInfo) => {
						//token超时
						uploader.stopUpload();
					},
				});
			},
			del(item) {
				this.imageList = this.imageList.filter(image => image.id != item.id)
				if (!this.imageList.length) {
					this.$emit('close')
				}
				this.$emit('changeImageList', this.imageList)
				this.$api_company.Image.Del(item.id)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uploadImageBox {
		display: flex;
	}

	.title {
		position: absolute;
		width: 215rpx;
		height: 215rpx;
		background: rgba(0, 0, 0, 0.3);
		z-index: 2;
		color: #fff;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 10rpx;
		box-sizing: border-box;
	}

	.imageAddBox {
		width: 215rpx;
		height: 215rpx;
		background-color: #f4f5f7;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		margin-right: 20rpx;
		margin-bottom: 8px;

		.success {
			z-index: 3;
			position: absolute;
			bottom: 0;
			right: 0;
			display: flex;
			flex-direction: row;
			border-style: solid;
			border-top-color: transparent;
			border-left-color: transparent;
			border-bottom-color: #5ac725;
			border-right-color: #5ac725;
			border-width: 9px;
			align-items: center;
			justify-content: center;

			>view {
				position: absolute;
				-webkit-transform: scale(0.7);
				transform: scale(0.7);
				bottom: -10px;
				right: -10px;
			}
		}

		.del {
			position: absolute;
			top: 0;
			right: 0;
			background-color: #373737;
			height: 14px;
			width: 14px;
			display: flex;
			flex-direction: row;
			border-bottom-left-radius: 100px;
			align-items: center;
			justify-content: center;
			z-index: 3;

			>view {
				position: absolute;
				-webkit-transform: scale(0.7);
				transform: scale(0.7);
				top: 0px;
				right: 0px;
			}
		}

		>image {
			width: 100%;
			height: 100%;
		}

		.uploadBox {
			position: absolute;
			background-color: rgba(0, 0, 0, 0.3);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: 20rpx;
			color: #fff;
			width: 100%;
			height: 100%;


		}
	}
</style>